<template>
    <div>
        <el-upload
            action="/student/avatarupload"
            name="avatar"
            list-type="picture-card"
            :headers="uploadHeaders"
            :before-upload="beforeUploadHandler"
            accept=".png,.jpg"
            :on-success="uploadSuccessHandler"
        >
            <i slot="default" class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
            </div>
        </el-upload>
    </div>
</template>

<script>
export default {
    name: "Aaa",
    data() {
        return {
            uploadHeaders: {
                Authorization: this.$cookies.get("token"),
            },
        };
    },
    methods: {
        uploadSuccessHandler(response, file, fileList) {
            console.log(response);
            if (response.status === 200) {
                if (fileList.length > 1) {
                    fileList.shift();
                } else {
                    this.$message.error(response.message);
                }
            }
        },
        // 在此函数内部对要上传的资源进行类型、大小等等验证
        beforeUploadHandler(file) {
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG || (isPNG && isLt2M);
        },
    },
};
</script>

<style lang="stylus" scoped>

</style>
